import { Store } from '../@zrv'
import counterReducer from '../reducers/counter'
import { increment, decrement } from '../actions/counter'

let interval;

const store = new Store({
    modules: {
        count: {
            state: 0,
            namespaced: true,
            baseReducer: counterReducer,
            reducers: {
                reset() {
                    return 0
                }
            },
            effects: {
                async increment({ commit }) {
                    commit(increment())
                },
                async decrement({ commit }) {
                    commit(decrement())
                },
                async play() {
                    if (interval) {
                        clearInterval(interval)
                    }
                    interval = setInterval(() => {
                        this.increment()
                    }, 500);
                },
                async stop() {
                    if (interval) {
                        clearInterval(interval)
                        interval = undefined
                    }
                }
            },
            selector: {
                count5(select) {
                    const count = select(state => state)
                    return count * 5
                }
            }
        }
    },
    watch: {
        count(curValue) {
            if (curValue === 10) {
                alert('Reset count to 0')
                setTimeout(() => {
                    this.count.reset()
                }, 2000);
            }
        }
    },
    selector: {
        count10(select) {
            const count = select(state => state.count)
            return count * 10
        }
    }
})

export default store;